import { v4 as guid } from 'uuid'

export function generateUUID (option) {
  return guid(option)
}

/**
 * 去除字符串首尾空格
 * @param str
 * @returns {*}
 */
 export function trim (str) {
  if (String.prototype.trim) {
    return str === null ? '' : String.prototype.trim.call(str)
  } else {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  }
}

/**
 * 去除字符串中所有空格
 * @param str
 * @returns {string | void | *}
 */
export function trimAll (str) {
  return str.replace(/\s*/g, '')
}

export function HTMLReplace (str) {
  let s = ''
  if (str.length === 0) return ''
  s = s.replace(/</g, '')
  s = s.replace(/>/g, '')
  return s
}

export function HTMLEncode (str) {
  let s = ''
  if (str.length === 0) return ''
  s = str.replace(/&/g, '&amp;')
  s = s.replace(/</g, '&lt;')
  s = s.replace(/>/g, '&gt;')
  s = s.replace(/ /g, '&nbsp;')
  // eslint-disable-next-line
  s = s.replace(/\'/g, '&#39;')
  // eslint-disable-next-line
  s = s.replace(/\"/g, '&quot;')
  return s
}

export function HTMLDecode (str) {
  let s = ''
  if (str.length === 0) return ''
  s = str.replace(/&amp;/g, '&')
  s = s.replace(/&lt;/g, '<')
  s = s.replace(/&gt;/g, '>')
  s = s.replace(/&nbsp;/g, ' ')
  // eslint-disable-next-line
  s = s.replace(/&#39;/g, "\'")
  s = s.replace(/&quot;/g, '"')
  return s
}

export function changeNumToHan (num) {
  var arr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  var arr2 = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']
  if (!num || isNaN(num)) return '零'
  var english = num.toString().split('')
  var result = ''
  for (var i = 0; i < english.length; i++) {
    var des_i = english.length - 1 - i// 倒序排列设值
    result = arr2[i] + result
    var arr1_index = english[des_i]
    result = arr1[arr1_index] + result
  }
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十') // 将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零+/g, '零') // 合并中间多个零为一个零
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万') // 将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/亿万/g, '亿') // 将【亿万】换成【亿】
  result = result.replace(/零+$/, '') // 移除末尾的零
  // 将【一十】换成【十】
  result = result.replace(/^一十/g, '十')
  return result
}

/**
 * 读取文本长度
 * @param {*} val 字符串
 * @param {*} num 一个汉字占2个字节（默认）
 * @returns
 */
export function getByteLen (val, num) {
  const charLen = num || 2
  let len = 0
  for (let i = 0; i < val.length; i++) {
    const a = val.charAt(i)
    if (a.match(/[^\x00-\xff]/ig) !== null) {
      len += charLen
    } else {
      len += 1
    }
  }
  return len
}

/**
 * 字符串转换成短(8)位hash
 * @param {*} str 字符串
 * @returns
 */
export function hashString(str) {
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) - hash) + str.charCodeAt(i)
    hash |= 0 // Convert to 32-bit integer
  }
  return hash.toString()
}
